﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core.Filter
{
    /// <summary>
    /// Return only the specified amount of entries.
    /// e.g. page=5,20 (Show the 5th page where each page have 20 items.)
    /// This is handled by individual list handler (e.g. AutoEntryList)
    /// </summary>
    [OptionFilter("page", -1)]
    public class PaginateOptionFilter : OptionFilterBase
    {
        public PaginateOptionFilter(int page = 1, int itemsPerPage = 20, string id = "page")
            : base(String.Format("{0},{1}", page, itemsPerPage), id)
        {
            Page = page;
            ItemsPerPage = itemsPerPage;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterString">e.g. 5,20</param>
        public PaginateOptionFilter(string filterString, string id)
            : base(filterString, id)
        {
            var filters = filterString.Split(',');
            if (filters.Length < 1)
                throw new ArgumentException("Invalid filterString");

            int page = Page = 1, itemsPerPage = ItemsPerPage = 20;

            if (Int32.TryParse(filters[0], out page))
                Page = page;

            if (filters.Length > 1)
                if (Int32.TryParse(filters[1], out itemsPerPage))
                    ItemsPerPage = itemsPerPage;                
        }

        public int Page { get; private set; }
        public int ItemsPerPage { get; private set; }
        public int Skip { get { return (Page-1) * ItemsPerPage; } }    
    }
}
